import {useState} from "react";

// useExportReport hook接口
interface UseExportReport {
    exportReport: () => Promise<void>;
    error1: string | null;
}

export function useExportReport(): UseExportReport {
    const [error1, setError] = useState<string | null>(null);
    const token = localStorage.getItem('token');

    const exportReport = async (): Promise<void> => {
        setError(null);
        try {
            if (!token) {
                setError('未提供授权令牌');
                return;
            }
            const response = await fetch('http://localhost:6868/admin/exportReport', {
                method: 'GET',
                headers: {
                    'Authorization': token!
                },
            });

            if (!response.ok) {
                throw new Error("导出报告失败");
            }

            // 假设服务器返回的是Blob对象
            const blob = await response.blob();
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = "report.csv"; // 假设导出的是Excel文件，根据实际情况修改文件名
            document.body.appendChild(a); // 添加元素到文档中
            a.click();
            a.remove(); // 下载后移除元素
            URL.revokeObjectURL(url); // 释放URL对象
        } catch (error1) {
            setError((error1 as Error).message);
        }
    };

    return {exportReport, error1};
}
